﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OleDb;
using System.Reflection;
using System.Data;
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net;
using MySite.Model;

namespace MySite.Helper
{
    public class Helper
    {

        public static string HashString(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            return BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input))).Replace("-", string.Empty);
        }

        public static bool VerifyCode(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                if (HttpContext.Current.Session[VerfiyCodeHandler.VERIFY_SESSION_KEY] != null)
                {
                    if (string.Equals(Convert.ToString(HttpContext.Current.Session[VerfiyCodeHandler.VERIFY_SESSION_KEY]),
                        input, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 默认字符串的长度为500
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ci"></param>
        /// <returns></returns>
        public OleDbParameter[] GetParametersByModelInfo<T>(T ci)
        {
            IList<OleDbParameter> paras = new List<OleDbParameter>();

            //从泛型ci中得到实体对象   把实体对象转化为PropertyInfo数组
            System.Reflection.PropertyInfo[] pi = ci.GetType().GetProperties();
            string PropertyValue = string.Empty;
            for (int i = 0; i < pi.Length; i++)
            {
                OleDbParameter para = new OleDbParameter();

                //pi[i].Name   得到实体属性值名称
                string PropertyName = ((System.Reflection.MemberInfo)(pi[i])).Name;
                PropertyInfo mi = ci.GetType().GetProperty(PropertyName);//得到属性
                PropertyValue = Convert.ToString(mi.GetValue(ci, null));
                if (PropertyValue != null)
                {
                    //属性SetValue
                    if (mi.PropertyType.ToString().Contains("Int32"))
                    {
                        para.IsNullable = false;
                        para.OleDbType = OleDbType.Integer;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                            
                    }
                    else if (mi.PropertyType.ToString().Contains("Double"))
                    {
                        para.IsNullable = false;
                        para.OleDbType = OleDbType.Double;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                    }
                    else if (mi.PropertyType.ToString().Contains("Decimal"))
                    {
                        para.IsNullable = false;
                        para.OleDbType = OleDbType.Decimal;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                    }
                    else if (mi.PropertyType.ToString().Contains("DateTime"))
                    {
                        para.IsNullable = false;
                        para.OleDbType = OleDbType.DBTimeStamp;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                    }
                    else
                    {
                        para.IsNullable = true;
                        para.OleDbType = OleDbType.VarChar;
                        para.Size = 500;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                    }
                }
            }

            return paras.ToArray();
        }

        /// <summary>
        /// 可指定某个属性的长度
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ci"></param>
        /// <param name="dict"></param>
        /// <returns></returns>
        public OleDbParameter[] GetParametersByModelInfo<T>(T ci,IDictionary<string,int> dict)
        {
            IList<OleDbParameter> paras = new List<OleDbParameter>();

            //从泛型ci中得到实体对象   把实体对象转化为PropertyInfo数组
            System.Reflection.PropertyInfo[] pi = ci.GetType().GetProperties();
            string PropertyValue = string.Empty;
            for (int i = 0; i < pi.Length; i++)
            {
                OleDbParameter para = new OleDbParameter();

                //pi[i].Name   得到实体属性值名称
                string PropertyName = ((System.Reflection.MemberInfo)(pi[i])).Name;
                PropertyInfo mi = ci.GetType().GetProperty(PropertyName);//得到属性
                PropertyValue = Convert.ToString(mi.GetValue(ci, null));
                if (PropertyValue != null)
                {
                    //属性SetValue
                    if (mi.PropertyType.ToString().Contains("Int32"))
                    {
                        para.IsNullable = false;
                        para.OleDbType = OleDbType.Integer;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;

                    }
                    else if (mi.PropertyType.ToString().Contains("Double"))
                    {
                        para.IsNullable = false;
                        para.OleDbType = OleDbType.Double;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                    }
                    else if (mi.PropertyType.ToString().Contains("Decimal"))
                    {
                        para.IsNullable = false;
                        para.OleDbType = OleDbType.Decimal;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                    }
                    else if (mi.PropertyType.ToString().Contains("DateTime"))
                    {
                        para.IsNullable = false;
                        para.OleDbType = OleDbType.DBTimeStamp;
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                    }
                    else
                    {
                        para.IsNullable = true;
                        para.OleDbType = OleDbType.VarChar;
                        para.Size = dict[PropertyName];
                        para.ParameterName = "@" + PropertyName;
                        para.Value = PropertyValue;
                    }
                }
            }

            return paras.ToArray();
        }

        /// <summary>
        /// 把DataRow转换为对应的ModelInfo
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <param name="ci"></param>
        /// <returns></returns>
        public static void GeneralModelInfo<T>(DataRow dr, ref T ci)
        {
           

             //从泛型ci中得到实体对象   把实体对象转化为PropertyInfo数组
            System.Reflection.PropertyInfo[] pi = ci.GetType().GetProperties();
            string PropertyValue = string.Empty;
            for (int i = 0; i < pi.Length; i++)
            {
                OleDbParameter para = new OleDbParameter();
                PropertyValue = string.Empty;
                //pi[i].Name   得到实体属性值名称
                string PropertyName = ((System.Reflection.MemberInfo)(pi[i])).Name;
                PropertyInfo mi = ci.GetType().GetProperty(PropertyName);//得到属性

                if (dr.Table.Columns.Contains(PropertyName))
                {
                    PropertyValue = Convert.ToString(dr[PropertyName]);
                }

                if (PropertyValue != null && PropertyValue != "")
                {
                    if (mi.PropertyType.ToString().Contains("Int32"))
                    {
                        mi.SetValue(ci, Convert.ChangeType(dr[PropertyName], typeof(System.Int32)), null);
                    }
                    else if (mi.PropertyType.ToString().Contains("Double"))
                    {
                        mi.SetValue(ci, Convert.ChangeType(dr[PropertyName], typeof(System.Double)), null);
                    }
                    else if (mi.PropertyType.ToString().Contains("Decimal"))
                    {
                        mi.SetValue(ci, Convert.ChangeType(dr[PropertyName], typeof(System.Decimal)), null);
                    }
                    else if (mi.PropertyType.ToString().Contains("DateTime"))
                    {
                        mi.SetValue(ci, Convert.ChangeType(dr[PropertyName], typeof(System.DateTime)), null);
                    }
                    else if (mi.PropertyType.ToString().Contains("MySite.Enum.BlogType"))
                    {
                        mi.SetValue(ci, System.Enum.Parse(typeof(MySite.Enum.BlogType), Convert.ToString(dr[PropertyName])), null);
                    }
                    else
                    {
                        mi.SetValue(ci, Convert.ChangeType(dr[PropertyName], mi.PropertyType), null);
                    }
                }
            }
        }

        #region 根据指定的modelInfo储存相关数据
        /// <summary>
        /// 根据指定的modelInfo储存相关数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="modelInfo"></param>
        /// <returns></returns>
        public static StringBuilder TSQLForInsertIntoAccess<T>(ref StringBuilder sb, T modelInfo, string FormName)
        {
            StringBuilder attrNamesb = new StringBuilder();

            StringBuilder valuesb = new StringBuilder();

            //从泛型ci中得到实体对象   把实体对象转化为PropertyInfo数组
            System.Reflection.PropertyInfo[] pi = modelInfo.GetType().GetProperties();
            string ColumnValue = string.Empty;
            for (int i = 0; i < pi.Length; i++)
            {
                //pi[i].Name   得到实体属性值名称
                string attrName = ((System.Reflection.MemberInfo)(pi[i])).Name;


                PropertyInfo mi = modelInfo.GetType().GetProperty(attrName);//得到属性
                //属性值

                if (attrName == "VisitResolution")
                {
                    ColumnValue =mi.GetValue(modelInfo, null).ToString();
                }
                else if (attrName == "VoteItems")
                {
                    ColumnValue = "";
                }
                else
                {
                    ColumnValue = Convert.ToString(mi.GetValue(modelInfo, null));
                }

                if (ColumnValue != "" && attrName != "PID")
                {
                    attrNamesb.AppendFormat("[{0}],", attrName);

                    if (mi.PropertyType.ToString().Contains("Boolean"))
                    {
                        valuesb.AppendFormat("'{0}',", Convert.ToBoolean(ColumnValue)?1:0);
                    }
                    else
                    {
                        valuesb.AppendFormat("'{0}',", ColumnValue);
                    }
                }

            }

            if (attrNamesb.Length > 0 && valuesb.Length > 0)
            {
                attrNamesb.Remove(attrNamesb.Length - 1, 1);
                valuesb.Remove(valuesb.Length - 1, 1);

                sb.AppendFormat("insert into {0} ({1}) values ({2}) @go@", FormName, attrNamesb, valuesb);
            }

            return sb;

        }
        #endregion

        #region 根据指定的modelInfo储存相关数据
        /// <summary>
        /// 根据指定的modelInfo储存相关数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="modelInfo"></param>
        /// <returns></returns>
        public static StringBuilder TSQLForUpdateAccess<T>(ref StringBuilder sb, T modelInfo, string FormName, string strID)
        {
            StringBuilder attrNamesb = new StringBuilder();

            StringBuilder valuesb = new StringBuilder();

            //从泛型ci中得到实体对象   把实体对象转化为PropertyInfo数组
            System.Reflection.PropertyInfo[] pi = modelInfo.GetType().GetProperties();
            string ColumnValue = string.Empty;
            for (int i = 0; i < pi.Length; i++)
            {
                //pi[i].Name   得到实体属性值名称
                string attrName = ((System.Reflection.MemberInfo)(pi[i])).Name;


                PropertyInfo mi = modelInfo.GetType().GetProperty(attrName);//得到属性
                //属性值
                ColumnValue = Convert.ToString(mi.GetValue(modelInfo, null));

                if (ColumnValue != "" && attrName != "PID")
                {
                    if (mi.PropertyType.ToString().Contains("Boolean"))
                    {
                        attrNamesb.AppendFormat("[{0}] = '{1}',", attrName, Convert.ToBoolean(ColumnValue)?1:0);
                    }
                    else
                    {
                        attrNamesb.AppendFormat("[{0}] = '{1}',", attrName, ColumnValue);
                    }
                }

            }

            if (attrNamesb.Length > 0)
            {
                attrNamesb.Remove(attrNamesb.Length - 1, 1);

                sb.AppendFormat("update {0} set {1} where PID = {2} @go@", FormName, attrNamesb, strID);
            }

            return sb;

        }
        #endregion

        #region 执行所有的sql语句
        /// <summary>
        /// 执行所有的sql语句
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="oledbConn"></param>
        /// <returns></returns>
        public static ReturnMessage ExecTSQL(StringBuilder sb, OleDbConnection oledbConn)
        {
            ReturnMessage rm = new ReturnMessage(true);

            if (oledbConn.State == ConnectionState.Closed && oledbConn.State != ConnectionState.Open)
            {
                oledbConn.Open();
            }

            OleDbTransaction otran = oledbConn.BeginTransaction(IsolationLevel.ReadUncommitted);
            string tempSql = "";
            string[] sqls = sb.ToString().Split(new string[]{"@go@"},StringSplitOptions.RemoveEmptyEntries);
            try
            {
                foreach (string sql in sqls)
                {
                    tempSql = sql;
                    if (sql != "")
                    {
                        using (OleDbCommand oledbcmd = new OleDbCommand(sql, oledbConn, otran))
                        {
                            oledbcmd.ExecuteNonQuery();
                        }
                    }
                }


                otran.Commit();
                rm.IsSuccessed = true;
            }
            catch (Exception e)
            {
                otran.Rollback();
                rm.IsSuccessed = false;
                rm.Text = string.Format("数据导入过程中出错!TSQL:{0}", tempSql);
                rm.Exception = e;
            }
            finally
            {
                otran.Dispose();
                oledbConn.Close();
            }

            return rm;
        }
        #endregion

        public static ReturnMessage SendMail(string title,string content)
        {
            ReturnMessage rm = new ReturnMessage();
            rm.IsSuccessed = true;

            string mailform = System.Configuration.ConfigurationManager.AppSettings["mailform"];
            string mailto = System.Configuration.ConfigurationManager.AppSettings["mailto"];
            string mailsmtp = System.Configuration.ConfigurationManager.AppSettings["smtp"];
            string mailaccount = System.Configuration.ConfigurationManager.AppSettings["mailaccount"];
            string mailpw = System.Configuration.ConfigurationManager.AppSettings["mailpassword"];

            System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
            mm.BodyEncoding = Encoding.UTF8;
            mm.SubjectEncoding = Encoding.UTF8;
            mm.Subject = title;
            mm.Body = content;
            mm.From =  new System.Net.Mail.MailAddress(mailform);
            mm.To.Add(new System.Net.Mail.MailAddress(mailto));

            mm.IsBodyHtml = true;
            SmtpClient client = new SmtpClient(mailsmtp); 
            client.UseDefaultCredentials = true;
            client.Credentials = CredentialCache.DefaultNetworkCredentials;
            //client.Credentials = new NetworkCredential(mailaccount, mailpw); 
            client.DeliveryMethod = SmtpDeliveryMethod.Network; 
            try { 
                client.Send(mm);
            }
            catch {
                rm.IsSuccessed = false;
            }
            

            return rm;
        }
    }

    
    
}
